package com.mini.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.*;

/**
 * @author zhangxiaobin
 * @title: ParamsRequestWrapper
 * @description: TODO
 * @date 2020/2/2219:47
 */
@Slf4j
public class ParamsRequestWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap<>();

    public ParamsRequestWrapper(HttpServletRequest request) {
        super(request);
        // 将参数表，赋予给当前的Map以便于持有request中的参数
        Map<String, String[]> requestMap = request.getParameterMap();
        log.info("转化前参数：【{}】" ,JSON.toJSONString(requestMap));
        this.params.putAll(requestMap);
        this.modifyParameters();
        log.info("转化后参数：【{}】" ,JSON.toJSONString(params));
    }

    /**
     * 将parameter的值去除空格后重写回去
     */
    private void modifyParameters() {
        Set<String> set = params.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            String key = it.next();
            String[] values = params.get(key);
            values[0] = values[0].trim();
            if("undefined".equalsIgnoreCase(values[0]) || "null".equalsIgnoreCase(values[0])){
                values[0]  = "";
            }
            params.put(key, values);
        }
    }

    /**
     * 重写getParameter 参数从当前类中的map获取
     */
    @Override
    public String getParameter(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(String name) {
        String[] values = params.get(name);
        if (values == null || values.length == 0) {
            return null;
        }
        return values;
    }

}
